<?php
namespace app\admin\controller;

use app\api\ext\IApiConfig;
use app\api\ext\ICryptAes;
use app\api\ext\IVerify;
use app\common\controller\AdminBaseController;
use app\common\ext\IRequest;
use think\Config;

class Api extends AdminBaseController{
    //token加密
    const CHECK_TOKEN      = '@%34YGYj23w&(*2e89r888';

    /**
     * @功能：客户APP API
     * @开发者：cxl
     * @return string
     */
    public function index(){
        //整理API列表信息
        $api_list = self::api_list(IApiConfig::$api,'api');

        //渲染画面
        $this->assign('data', 'aaa');
        $this->assign('api_list', $api_list['api']);
        $this->assign('api_param', json_encode($api_list['param']));

        //模板输出
        return view('index');
    }

    /**
     * 信贷APP API
     * @return \think\response\View
     */
    public function xd(){
        //整理API列表信息
        $api_list = self::api_list(\app\credit\ext\IApiConfig::$api,'credit');

        //渲染画面
        $this->assign('data', 'aaa');
        $this->assign('api_list', $api_list['api']);
        $this->assign('api_param', json_encode($api_list['param']));

        //模板输出
        return view('index');
    }

    /**
     * 合作端APP API
     * @return \think\response\View
     */
    public function hz(){
        //整理API列表信息
        $api_list = self::api_list(\app\partner\ext\IApiConfig::$api,'partner');

        //渲染画面
        $this->assign('data', 'aaa');
        $this->assign('api_list', $api_list['api']);
        $this->assign('api_param', json_encode($api_list['param']));

        //模板输出
        return view('index');
    }

    /**
     * @功能：取得API列表
     * @return bool
     */
    public function api_call(){
        //接收参数
        $api_url = IRequest::get("api_url"); //地址
        $api_controller = IRequest::get("api_controller"); //取得API的控制器名称
        $api_action = IRequest::get("api_action"); //取得API的方法名称

        //初期化返回值
        $api_json=null;
        $api_json['status'] = "OK";
        $api_json['info'] = "操作成功！";

        //判断是否为取得token
        $data = null;
        if(!(strtolower($api_controller) == "system" && strtolower($api_action) == "start")){
            //生产token
            $data['_t']['_u'] = IRequest::get("_u");
            $data['_t']['_d'] = IRequest::get("_d");
            $data['_t']['_o'] = IRequest::get("_o");
            $data['_t']['_v'] = IRequest::get("_v");
            $data['_t']['_e'] = time() + 3600 * 24;
            $data['_t']['_r'] = rand(0,10000); //随机数

            //token加密前
            $api_json['token'] = print_r($data['_t'],true);
        }

        //取得参数值
        foreach($_POST as $key=>$val){
            //判断是否为token值
            if(!in_array($key,array('_u','_d','_o','_v','m','PHPSESSID','api_controller','api_action'))){
                $data[$key] = $val;
            }
        }

        //加密数据
        $api_json['parameter'] = print_r($data,true);
        $param = IVerify::encrypt($data);

        if(empty($param)){
            $api_json['status'] = "NG";
            $api_json['info'] = "数据加密错误！";
            echo json_encode($api_json);
            exit;
        }else{
            $api_json['request'] = $param;
        }

        //调用接口
        $result = self::curl_post($api_url,array("_param"=>$param));
        if(empty($result)){
            $api_json['status'] = "NG";
            $api_json['info'] = "调用接口失败！";
            echo json_encode($api_json);
            exit;
        }else{
            $api_json['response'] = $result;
        }

        //解析接口数据
        $result = ICryptAes::decrypt($result);
        if(empty($result)){
            $api_json['status'] = "NG";
            $api_json['info'] = "解析接口返回值失败！";
            echo json_encode($api_json);
            exit;
        }

        //解析接口数据
        $result = json_decode($result,true);
        if(empty($result)){
            $api_json['status'] = "NG";
            $api_json['info'] = "解析接口返回值失败！";
            echo json_encode($api_json);
            exit;
        }else{
            $api_json['result'] = print_r($result,true);
        }

        //页面赋值
        echo json_encode($api_json);
        exit;
    }

    /**
     * @功能：取得API列表
     * @param $api_temp
     * @param $api_module
     * @return array
     */
    private static function api_list($api_temp,$api_module){
        //取得配置信息
        $api_list = array();

        //循环整理API列表信息
        foreach($api_temp as $item=>$value){
            //设置控制器及方法名
            list($api_controller,$api_action) = explode("/",$item);

            //取得IP地址
            $ip = Config::get("domain");

            //保存数据
            $api_list['api'][$value['api_group']][$item] = $value;
            $api_list['api'][$value['api_group']][$item]['api_url'] = "http://{$ip}/{$api_module}/{$item}.html";
            $api_list['api'][$value['api_group']][$item]['api_controller'] = $api_controller;
            $api_list['api'][$value['api_group']][$item]['api_action'] = $api_action;

            //参数数据
            $api_list['param'][$item] = $value['api_param'];
        }

        //放回接口列表信息
        return $api_list;
    }

    /**
     * @功能：发起HTTPS请求
     * @param string $url 请求地址
     * @param string $data 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
     * @return bool
     */
    private static function curl_post($url,$data){
        //参数设置
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-Type"=>"application/json;charset=utf-8"));

        //发送请求
        $result = curl_exec ($ch);

        //关闭
        curl_close($ch);

        //返回值
        return $result;
    }
}
